"use strict";

const Service = require("egg").Service;

class StudentService extends Service {
    /**
     * 学生列表
     */
    async readList() {
        let sql = `
            select
                s.id as student_id,
                s.realname as student_name,
                s.code as student_code,
                s.password as student_password,
                r.id as room_id,
                r.name as room_name,
                g.id as grade_id,
                g.name as grade_name
            from
            student as s
            join grade as g on s.gid = g.id
            join room as r on g.rid = r.id
        `;
        let res = await this.app.mysql.query(sql);
        return res;
    }

    /**
     * 根据学生id，查找某个学生
     * @param {string} id 学生id
     */
    async find(id) {
        let sql = "select * from student where id = ? limit 0, 1";
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 根据学生code，查找某个学生
     * @param {string} code
     */
    async findByCode(code) {
        let sql = "select * from student where code = ? limit 0, 1";
        let params = [code];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 添加学生
     */
    async add({ realname, code, password, gid }) {
        // 检查班级是否存在
        const grade = await this.service.grade.find(gid);
        if (!grade) {
            this.ctx.cast(404, "该班级不存在");
        }
        // 学生是否已经存在（学号唯一）
        const student = await this.findByCode(code);
        if (student) {
            this.ctx.cast(404, "该学号已存在");
        }
        // 入库
        let sql =
            "insert into student (id, realname, code, password, gid) values (?, ?, ?, ?, ?)";
        let params = [this.ctx.helper.uuid(), realname, code, password, gid];
        let res = await this.app.mysql.query(sql, params);
        return {
            id: res.insertId,
            rows: res.affectedRows,
        };
    }

    /**
     * 删除一个学生
     * @param {*} id
     */
    async remove(id) {
        // 学生不存在
        const student = await this.find(id);
        if (!student) {
            this.ctx.cast(404, "该学生不存在");
        }
        // 删除学生
        let sql = "delete from student where id = ?";
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return {
            rows: res.affectedRows,
        };
    }
}

module.exports = StudentService;
